package com.xzz.directprint.util;


import com.spire.pdf.PdfDocument;
import lombok.Data;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-11-17 14:41
 * @FullNameClass: com.xzz.directprint.util.PdfPrintUtil
 * @Description: https://blog.csdn.net/qq_52010446/article/details/131465685
 * 未使用，不打印图片
 */
@Component
@Data
public  class PdfPrintUtil {

    @Value("${pdf.path}")
    private String pdfpath;

    @Value("${pdf.expanded-name}")
    private String expandName;

    public  boolean print(String filePath){
        boolean flag = false;
        //Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        //Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        //Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        //Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        //Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        try{
            //Load a PDF file
            String file = pdfpath.concat(filePath).concat(expandName);
            pdf.loadFromFile(file);
        }catch (Exception ex){
            System.out.println("文件不存在！");
        }


        //Call painter to render the pages in the specified format
        printerJob.setPrintable(pdf, pageFormat);

        //Execute printing
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
            System.out.println("请检测PDF文件是否存在！");
            flag = true;
        }finally {
            return flag;
        }
    }
}
